package com.load.utils;

import java.util.*;

import org.tmatesoft.svn.core.*;
import org.tmatesoft.svn.core.auth.*;
import org.tmatesoft.svn.core.internal.io.dav.*;
import org.tmatesoft.svn.core.internal.io.fs.*;
import org.tmatesoft.svn.core.io.*;
import org.tmatesoft.svn.core.wc.*;

import com.google.common.collect.*;
import com.load.objects.*;

public class SVNUtil {

	public static Collection<?> getEntries(SVNRepository repository) throws SVNException {
		long startRevision = 2;
		long endRevision = repository.getLatestRevision();
		Collection<?> entries = repository.log(new String[] { "" }, null, startRevision, endRevision, true, true);
		return entries;
	}

	public static SVNRepository configureRepository(String url, String login, String password) throws SVNException {
		DAVRepositoryFactory.setup();
		FSRepositoryFactory.setup();
		SVNRepository repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));

		ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(login, password);
		repository.setAuthenticationManager(authManager);

		repository.getLatestRevision();

		return repository;
	}

	public static List<MySVNDirEntry> getCurrentJavaEntries(SVNRepository repository, String path) throws SVNException {
		List<MySVNDirEntry> currentEntries = new ArrayList<MySVNDirEntry>();

		Collection<?> entries = repository.getDir(path, -1, null, Lists.newArrayList());
		Iterator<?> iterator = entries.iterator();

		while (iterator.hasNext()) {
			SVNDirEntry entry = (SVNDirEntry) iterator.next();

			String pathDir = "";
			if (entry.getKind() == SVNNodeKind.DIR) {
				pathDir = path.equals("") ? entry.getName() : path + "/" + entry.getName();
				currentEntries.addAll(getCurrentJavaEntries(repository, pathDir));
			} else if (entry.getKind() == SVNNodeKind.FILE) {
				pathDir = "/" + (path.equals("") ? "" : path + "/") + entry.getName();
				if (FileUtil.pathIsFileOO(pathDir)) {
					MySVNDirEntry myEntry = new MySVNDirEntry(entry, pathDir);
					currentEntries.add(myEntry);
				}
			}
		}

		return currentEntries;
	}

}